import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'

const prisma = new PrismaClient()

/**
 * @swagger
 * /api/users:
 *   get:
 *     summary: 获取用户列表
 *     responses:
 *       200:
 *         content:
 *           application/json:
 *             example:
 *               - id: "123"
 *                 name: "张三"
 *                 email: "zhangsan@example.com"
 *                 role: "管理员"
 *   post:
 *     summary: 创建用户
 *     requestBody:
 *       content:
 *         application/json:
 *           example:
 *             name: "张三"
 *             email: "zhangsan@example.com"
 *             role: "用户"
 */

export async function GET() {
  try {
    const users = await prisma.user.findMany()
    return NextResponse.json(users)
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch users' }, { status: 500 })
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const hashedPassword = await bcrypt.hash('123456', 10) // 默认密码 123456

    const user = await prisma.user.create({
      data: {
        name: body.name,
        email: body.email,
        role: body.role,
        password: hashedPassword  // 添加默认密码
      },
    })
    
    // 返回时不包含密码
    const { password, ...userWithoutPassword } = user
    return NextResponse.json(userWithoutPassword)
  } catch (error) {
    console.error('创建用户失败', error)
    return NextResponse.json({ error: '创建用户失败' }, { status: 500 })
  }
} 